<template>
    <div class="app-container">
        <el-row :gutter="20">
            <el-col :span="12">
                <el-card>
                    <div slot="header" class="clearfix">
                        <h3>第一步：修改档案基本信息</h3>
                    </div>
                    <el-form ref="archiveRef" :model="form" :rules="rules" label-position="top" label-width="85px">
                        <el-form-item label="档案名称" prop="name">
                            <el-input v-model="form.name" placeholder="请输入档案名称" style="width: 100%;" />
                        </el-form-item>
                        <div
                            style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                            <el-form-item label="起始时间(档案内文件的最早时间)" prop="startDate" width="100%">
                                <el-date-picker clearable v-model="form.startDate" type="date" value-format="YYYY-MM-DD"
                                    placeholder="请选择起始时间">
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="终止时间(档案内文件的最晚时间)" prop="endDate" width="100%">
                                <el-date-picker clearable v-model="form.endDate" type="date" value-format="YYYY-MM-DD"
                                    placeholder="请选择终止时间">
                                </el-date-picker>
                            </el-form-item>
                            <el-form-item label="归档时间(收藏于档案馆的时间)" prop="guidangTime">
                                <el-date-picker clearable v-model="form.guidangTime" type="date"
                                    value-format="YYYY-MM-DD" placeholder="请选择归档时间">
                                </el-date-picker>
                            </el-form-item>
                        </div>
                        <div
                            style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                            <el-form-item label="档案门类" prop="category" width="100%">
                                <el-select v-model="form.categoryId" placeholder="请选择所属类别">
                                    <el-option v-for="category in categoryList" :key="category.id"
                                        :label="category.name" :value="category.id"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="载体类型" prop="carrierType" width="100%">
                                <el-select v-model="form.carrierType" placeholder="请选择载体类型">
                                    <el-option v-for="dict in iams_carrier_type" :key="dict.value" :label="dict.label"
                                        :value="dict.value"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="保管期限" prop="retentionPeriod" width="100%">
                                <el-select v-model="form.retentionPeriod" placeholder="请选择保管期限">
                                    <el-option v-for="dict in iams_retention_period" :key="dict.value"
                                        :label="dict.label" :value="dict.value"></el-option>
                                </el-select>
                            </el-form-item>
                        </div>
                        <div
                            style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                            <el-form-item label="保密级别" prop="secretLevel" width="100%">
                                <el-select v-model="form.secretLevel" placeholder="请选择保密级别">
                                    <el-option v-for="dict in iams_secret_level" :key="dict.value" :label="dict.label"
                                        :value="dict.value"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="保密期限" prop="secretPeroid">
                                <el-select v-model="form.secretPeroid" placeholder="请选择保密期限" width="100%">
                                    <el-option v-for="dict in iams_secret_period" :key="dict.value" :label="dict.label"
                                        :value="dict.value"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="解密日期" prop="desecretDate" width="100%">
                                <el-date-picker clearable v-model="form.desecretDate" type="date"
                                    value-format="YYYY-MM-DD" placeholder="请选择解密日期">
                                </el-date-picker>
                            </el-form-item>
                        </div>
                        <div
                            style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                            <el-form-item label="所属全宗" prop="fonds" width="100%">
                                <el-select v-model="form.fondsId" placeholder="请选择所属全宗">
                                    <el-option v-for="fonds in fondsList" :key="fonds.id" :label="fonds.name"
                                        :value="fonds.id"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="形成单位" prop="formationUnit" style="width: 50%;">
                                <el-input v-model="form.formationUnit" placeholder="请输入形成单位" />
                            </el-form-item>
                            <el-form-item label="移交单位" prop="transferUnit" style="width: 50%;">
                                <el-input v-model="form.transferUnit" placeholder="请输入移交单位" />
                            </el-form-item>
                        </div>
                        <el-form-item label="档案简介" prop="description">
                            <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
                        </el-form-item>
                        <div
                            style="display: flex; flex-direction: row; justify-content: space-between; align-items: center;">
                            <el-form-item label="电子档案位置" prop="dianziLocation" style="width: 50%;">
                                <el-input v-model="form.dianziLocation"
                                    placeholder="请输入电子档案存储位置，如 C:\ProgramData\Alibaba\AlibabaProtectDT" />
                            </el-form-item>
                            <el-form-item label="实体档案位置(格式:1-2-A)" prop="shitiLocation" style="width: 50%;">
                                <el-input v-model="form.shitiLocation" placeholder="请输入实体档案存放位置，如 1-2-A" />
                            </el-form-item>
                        </div>
                        <el-form-item label="档案编号" prop="danghao">
                            <el-input v-model="form.danghao" placeholder="请输入档号(可以根据上面的基本信息按指定规则生成)" width="100%">
                                <template #append>
                                    <el-button type="primary" @click="handelGenerateDanghao">点击生成</el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="射频标签号" prop="rfid">
                            <el-input v-model="form.rfid" placeholder="请输入射频标签号(可以根据档案编号按指定规则生成)" width="100%">
                                <template #append>
                                    <el-button type="primary" @click="handelRfid">自动生成</el-button>
                                </template>
                            </el-input>
                        </el-form-item>
                        <el-form-item label="备注" prop="remark">
                            <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
                        </el-form-item>
                        <el-form-item label="额外信息" prop="extraInfo">
                            <el-button type="primary" @click="showDialog">修改</el-button>
                        </el-form-item>
                    </el-form>
                    <template #footer>
                        <el-button @click="cancel">取 消</el-button>
                        <el-button type="primary" @click="submitForm">提 交</el-button>
                    </template>
                </el-card>
            </el-col>
            <el-col :span="12">
                <el-card class="box-card">
                    <template #header>
                        <div class="clearfix">
                            <h3>第二步：修改档案目录</h3>
                        </div>
                    </template>
                    <el-tree style="max-width: 90%" :data="dataSource" show-checkbox node-key="id" default-expand-all
                        :draggable="true" :expand-on-click-node="false">
                        <template #default="{ node, data }">
                            <span class="custom-tree-node">
                                <span>{{ node.label }}</span>
                                <span>
                                    <a @click="editTreeNode(data)"> 编辑 </a>
                                    <a style="margin-left: 8px" @click="appendTreeNode(data)"> 追加 </a>
                                    <a style="margin-left: 8px" @click="removeTreeNode(node, data)"> 删除 </a>
                                </span>
                            </span>
                        </template>
                    </el-tree>
                    <template #footer>
                        <el-button type="primary" @click="saveDirectory">保 存</el-button>
                    </template>
                </el-card>
            </el-col>
        </el-row>
        <el-dialog v-model="dialogFormVisible" title="档案额外信息" width="550">
            <el-form :model="extraInfo">
                <!-- 动态生成每个 div -->
                <div v-for="(info, index) in extraInfoList" :key="index"
                    style="display: flex; align-items: center; margin-bottom: 16px;">
                    <el-form-item label="属性" style="margin-right: 16px; margin-bottom: 0;">
                        <el-input v-model="info.label" autocomplete="off" style="width: 180px;" />
                    </el-form-item>
                    <el-form-item label="内容" style="margin-right: 16px; margin-bottom: 0;">
                        <el-input v-model="info.value" autocomplete="off" style="width: 180px;" />
                    </el-form-item>
                    <!-- 减号按钮 -->
                    <el-button v-if="extraInfoList.length > 1" type="danger" @click="removeExtraInfo(index)"
                        :icon="Minus" circle style="margin-left: 8px;"></el-button>
                </div>
                <!-- 加号按钮 -->
                <div style="display: flex; justify-content: center; margin-top: 16px;">
                    <el-button type="primary" @click="addExtraInfo" :icon="Plus" circle></el-button>
                </div>
            </el-form>
            <template #footer>
                <div class="dialog-footer" style="text-align: right;">
                    <el-button @click="cancelDialog">取消</el-button>
                    <el-button type="primary" @click="saveExtraInfoList">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup name="add">
import { ref, reactive, onMounted } from 'vue'
import { useRoute } from 'vue-router';
import { addArchive, getArchive, updateArchive, getNextArchiveNumber } from '@/api/manage/archive'
import { listDirectory } from "@/api/manage/directory";
import { listCategory } from "@/api/manage/category";
import { listFonds } from "@/api/manage/fonds";
import { Plus, Minus } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance()
const { iams_carrier_type, iams_retention_period, iams_secret_period, iams_secret_level } = proxy.useDict('iams_carrier_type', 'iams_retention_period', 'iams_secret_period', 'iams_secret_level');

const route = useRoute();

const data = reactive({
    form: {
        danghao: null,
        name: null,
        secretLevel: null,
        secretPeroid: null,
        desecretDate: null,
        retentionPeriod: null,
        carrierType: null,
        startDate: null,
        endDate: null,
        guidangTime: null,
        location: null,
        description: null,
        formationUnit: null,
        transferUnit: null,
        documentCount: null,
        extraInfo: null,
    },
    rules: {
        name: [
            { required: true, message: "档案名称不能为空", trigger: "blur" }
        ],
    }
});
const { form, rules } = toRefs(data);

const extraInfoList = ref([{ label: '', value: '' }]);
const dialogFormVisible = ref(false)
const extraInfo = reactive({
    label: '',
    value: '',
})
function showDialog() {
    dialogFormVisible.value = true
}
function cancelDialog() {
    dialogFormVisible.value = false
    extraInfoList.value = [{ label: '', value: '' }];
}
function addExtraInfo() {
    extraInfoList.value.push({ label: '', value: '' });
}

function saveExtraInfoList() {
    if (extraInfoList.value.length === 0) {
        proxy.$message({
            message: '请至少添加一个额外信息',
            type: 'warning'
        });
        return;
    }
    form.value.extraInfo = JSON.stringify(extraInfoList.value);
    proxy.$modal.msgSuccess("额外信息保存成功");
    dialogFormVisible.value = false;
}

function removeExtraInfo(index) {
    extraInfoList.value.splice(index, 1);
}

// 取消按钮
function cancel() {
    reset();
}

// 表单重置
function reset() {
    form.value = {
        id: null,
        danghao: null,
        name: null,
        rfid: null,
        jianhao: null,
        secretLevel: null,
        secretPeroid: null,
        desecretDate: null,
        retentionPeriod: null,
        carrierType: null,
        startDate: null,
        endDate: null,
        guidangTime: null,
        location: null,
        description: null,
        formationUnit: null,
        transferUnit: null,
        documentCount: null,
        status: null,
        authenticity: null,
        integrity: null,
        availability: null,
        security: null,
        categoryId: null,
        fondsId: null,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null,
        remark: null
    };
    proxy.resetForm("archiveRef");
}

/** 提交按钮 */
function submitForm() {
    proxy.$refs["archiveRef"].validate(valid => {
        if (valid) {
            updateArchive(form.value).then(response => {
                proxy.$modal.msgSuccess("修改成功");
                proxy.$router.push({ path: "/manage/archive/arc-list" });
            });
        }
    });
}

// 查询分类列表
const categoryList = ref([]);
/** 查询档案门类管理列表 */
function getCategoryList() {
    listCategory({}).then(response => {
        categoryList.value = response.rows;
    });
    console.log(categoryList.value);
}
getCategoryList();
// 全宗列表
const fondsList = ref([]);
/** 查询全宗列表 */
function getFondsList() {
    listFonds({}).then(response => {
        fondsList.value = response.rows;
    });
}
getFondsList();

/**
 * @typedef {Object} Tree
 * @property {number} id
 * @property {string} label
 * @property {string[]} files
 * @property {Tree[]} [children]
 */

const defaultProps = {
    children: 'children',
    label: 'label',
    files: 'files',
    id: 'id'
}

let id = 1000

const dataSource = ref([
    {
        id: 1,
        label: 'Level one 1',
        files: [],
        children: [
            {
                id: 4,
                label: 'Level two 1-1',
                files: [],
                children: [
                    {
                        id: 9,
                        label: 'Level three 1-1-1',
                        files: [],
                    },
                    {
                        id: 10,
                        label: 'Level three 1-1-2',
                        files: [],
                    },
                ],
            },
        ],
    },
    {
        id: 2,
        label: 'Level one 2',
        files: [],
        children: [
            {
                id: 5,
                label: 'Level two 2-1',
                files: [],
            },
            {
                id: 6,
                label: 'Level two 2-2',
                files: [],
            },
        ],
    },
    {
        id: 3,
        label: 'Level one 3',
        files: [],
        children: [
            {
                id: 7,
                label: 'Level two 3-1',
                files: [],
            },
            {
                id: 8,
                label: 'Level two 3-2',
                files: [],
            },
        ],
    },
])

/**
 * 编辑树节点
 * @param {Tree} data
 */
const editTreeNode = (data) => {
    data.label = '被修改了的目录'
    dataSource.value = [...dataSource.value]
}

/**
 * 追加树节点
 * @param {Tree} data
 */
const appendTreeNode = (data) => {
    const newChild = { id: id++, label: '一个新增的目录', files: [], children: [] }
    if (!data.children) {
        data.children = []
    }
    data.children.push(newChild)
    dataSource.value = [...dataSource.value]
}

/**
 * 移除树节点
 * @param {Node} node
 * @param {Tree} data
 */
const removeTreeNode = (node, data) => {
    const parent = node.parent
    const children = parent.data.children || parent.data
    const index = children.findIndex((d) => d.id === data.id)
    children.splice(index, 1)
    dataSource.value = [...dataSource.value]
}

// 保存修改后的档案目录结构
function saveDirectory() {
    // updateArchive(form.value).then(response => {
    //     proxy.$modal.msgSuccess("修改成功");
    //     proxy.$router.push({ path: "/manage/archive/arc-list" });
    // });
}

function handelGenerateDanghao() {
    if (!form.value.guidangTime || !form.value.categoryId) {
        proxy.$message({
            message: '请先选择归档时间和档案门类',
            type: 'warning'
        });
        return;
    }

    const [year, month, day] = form.value.guidangTime.split('-');
    const categoryId = form.value.categoryId;

    getNextArchiveNumber(categoryId).then(response => {
        const nextNumber = response.msg;
        form.value.danghao = `${year}${month}${day}${categoryId}${nextNumber.toString().padStart(4, '0')}`;
    }).catch(error => {
        proxy.$message({
            message: '生成档号失败，请稍后再试',
            type: 'error'
        });
    });
}

function handelRfid() {
    const length = 16;
    const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let result = '';
    const charactersLength = characters.length;
    for (let i = 0; i < length; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    form.value.rfid = result;
}

onMounted(() => {
    reset();
    const _id = route.query.id;
    getArchive(_id).then(response => {
        form.value = response.data;
        console.log(response.data);
        dataSource.value = JSON.parse(response.data.directory);
        extraInfoList.value = JSON.parse(response.data.extraInfo);
    });
});

</script>

<style>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
</style>
